import threading
import Queue
import os
import time
import copy
import sysinfo
import datetime

class HostMonitor:

    def __init__(self):
        self._dia = DynamicInfoAgent()

    def getPlatformInfo(self):
        return sysinfo.get_platform_info()

    def getVMConfig(self, Uuid):
        return sysinfo.get_vm_config(Uuid)

    def getDynamicInfo(self):
        return self._dia.getDynamicInfo()

    def getDynamicInfos(self, secs):
        return self._dia.getDynamicInfos(secs)

    def getHistoryInfos(self, from_time, to_time,Uuid = None):
        if os.access('/proc/xen', os.R_OK) == True:
            return self._dia.getVMHistoryInfos(from_time, to_time, Uuid)
        else:
            return self._dia.getPMHistoryInfos(from_time, to_time)

class DynamicInfoAgent(object):

    def __init__(self):
        self._lock = threading.Lock()
        self._q = Queue.Queue(maxsize = 10)
        self._l = [{} for i in xrange(0, 30)]
              

        producer = threading.Thread(target = self._produce_dynamic_info)
        producer.setDaemon(True)
        producer.start()

        consumer = threading.Thread(target = self._store_to_database)
        consumer.setDaemon(True)
        consumer.start()

    def _produce_dynamic_info(self):
        while True:
            info = sysinfo.get_dynamic_info()

            self._lock.acquire()
            self._l = self._l[:-1]
            self._l.insert(0, info)
            try:
                self._q.put_nowait(info)
            except:
                pass
            self._lock.release()

            time.sleep(1)

    def _store_to_database(self):
        
        while True:
            info = self._q.get()
            try:
                db_server.save_dynamic_info(info)
            except:
                pass
              
    def getDynamicInfo(self):
        self._lock.acquire()
        info = copy.deepcopy(self._l[0])
        self._lock.release()
        return info

    def getDynamicInfos(self, secs):
        self._lock.acquire()
        infos = copy.deepcopy(self._l[0:secs])
        self._lock.release()
        return infos

    def getPMHistoryInfos(self, from_time, to_time):
        if abs(to_time - from_time) > 300:
            return []
        return db_server.get_data(from_time, to_time, flag = "phy_info")
        

if __name__ == "__main__":
    import vnixglobal
    import time
    hd = HostMonitor()
    while True:
        print hd.getHistoryInfos(time.time()-3,time.time())
        time.sleep(1)
 


